package main

import (
    "database/sql"
    "errors"
    "fmt"
    "go.uber.org/zap"
    "google.golang.org/protobuf/proto"
    "laxkits/lib/laxmysql"
    "laxkits/lib/laxoffice"
    KKSG "laxkits/lib/ropb"
    "strconv"
)

func DoSync(conn *laxmysql.LaxMySQLConn, roleid uint64, openId, name string) error {
    zap.S().Infof("准备同步[%s] [%d], [%s]", openId, roleid, name)
    var modify = false
    for i := 1; i < 21 && !modify; i++ {
        conn.QueryRow(fmt.Sprintf("select role%d from world.account where id = ?", i), func(row *sql.Row) error {
            var brief KKSG.RoleBriefInfo
            var b []byte
            if err := row.Scan(&b); err != nil {
                return err
            }
            if err := proto.Unmarshal(b, &brief); err != nil {
                return err
            }
            if brief.RoleID == roleid {
                brief.Name = name
                b, err := proto.Marshal(&brief)
                if err != nil {
                    return err
                }
                affect, err := conn.Execute(fmt.Sprintf("update world.account set role%d = ? where id = ?", i), b, openId)
                if err != nil {
                    zap.S().Infof("账号[%s] id[%d] 名字[%s]同步失败:%v", openId, roleid, name, err)
                    return err
                }
                zap.S().Infof("账号[%s] id[%d] 名字[%s]同步成功,影响行:%d,下标:%d", openId, roleid, name, affect, i)
                modify = true
            }
            return nil
        }, openId)
    }
    return nil
}

func TrySyncName(csvIndex int, csvRow []string) error {
    if len(csvRow) < 11 {
        zap.S().Errorf("处理行出错:%d, %s", csvIndex, csvRow)
        return errors.New("ModifyError")
    }
    roleId, err := strconv.ParseUint(csvRow[0], 10, 64)
    if err != nil {
        zap.S().Errorf("解析roleid出错,行:%d,%s", csvIndex, csvRow)
        return err
    }
    sid := csvRow[2]
    conn := laxmysql.GetLaxMySQLMgr().GetById(sid)
    if conn == nil {
        zap.S().Errorf("服务器:%s,没有相应的mysqlconn, 行:%d,%s", sid, csvIndex, csvRow)
        return errors.New("SidError")
    }
    if err = conn.QueryRow(fmt.Sprintf("select name, account from player%d.role where id=?",roleId % 5), func(row *sql.Row) error {
        var curName , openId string
        if err = row.Scan(&curName, &openId); err != nil {
            return err
        }
        DoSync(conn, roleId, openId, curName)
        return nil
    }, roleId) ; err != nil {
        if err == sql.ErrNoRows {
            zap.S().Infof("角色没有，不用同步,rowIndex[%d],[%s]", csvIndex, csvRow)
            return nil
        }
        return err
    }

    return nil
}

func TypeSync() {
    if err := laxoffice.CSVEachRow("./modify.csv", 2, TrySyncName); err != nil {
        zap.S().Warnf("读取csv出错:%v", err)
        return
    }
}
